package com.sihan.framework.etm.service.business.impl;

import com.framework.model.PageResult;
import com.framework.util.PageUtils;
import com.github.pagehelper.PageHelper;
import com.sihan.framework.etm.common.AppConfiguration;
import com.sihan.framework.etm.common.util.DateUtils;
import com.sihan.framework.etm.common.util.ImgUtils;
import com.sihan.framework.etm.dto.business.ToolOverviewDTO;
import com.sihan.framework.etm.enums.FormatImgPre;
import com.sihan.framework.etm.mapper.business.StatisticalAnalysisMapper;
import com.sihan.framework.etm.service.business.StatisticalAnalysisService;
import com.sihan.framework.etm.vo.business.*;
import com.sihan.framework.etm.vo.statistics.BaseTypeVO;

import lombok.RequiredArgsConstructor;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.stream.Collectors;

/**
 * @author gyz
 * @version 1.0
 * @since jdk1.8
 */
@Component
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class StatisticalAnalysisServiceImpl implements StatisticalAnalysisService {

	private final StatisticalAnalysisMapper statisticalAnalysisMapper;

	private final ImgUtils imgUtils;
	
	private final AppConfiguration appConfig;

	@Override
	public PageResult<ToolOverviewVO> getToolOverview(ToolOverviewDTO dto) {
		if(!StringUtils.isBlank(dto.getCheckStartDate())) {
			dto.setCheckStartDate(dto.getCheckStartDate() + " 00:00:00:000");
		}
		if(!StringUtils.isBlank(dto.getCheckEndDate())) {
			dto.setCheckEndDate(dto.getCheckEndDate() + " 23:59:59:999");
		}
		PageHelper.startPage(dto);
		List<ToolOverviewVO> toolOverviews = statisticalAnalysisMapper.getToolOverview(dto);
		if(null != toolOverviews && !toolOverviews.isEmpty()) {
			toolOverviews.stream().forEach(vo->{
				if("入库".equals(vo.getStatus())) {
					vo.setBorrowUser(null);
					vo.setBorrowUserName(null);
					vo.setBorrowUserPhone(null);
					vo.setBorrowUser(null);
				}
				if(null != vo.getElectricityQuantity()) {
					vo.setElectricityQuantity(vo.getElectricityQuantity().multiply(new BigDecimal(100)).
							divide(appConfig.getVoltageTotal(), 2, RoundingMode.DOWN));
				}
				vo.setLastInspectionDate(StringUtils.isBlank(vo.getLastInspectionDate())?"":vo.getLastInspectionDate().substring(0, 10));
				vo.setExpiredDate(StringUtils.isBlank(vo.getExpiredDate())?"":vo.getExpiredDate().substring(0, 10));
			});
		}
		return PageUtils.toPageResult(toolOverviews);
	}

	@SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
	public Map getToolDetailInfo(String toolId) {
		BaseToolInfo baseToolMainInfo = statisticalAnalysisMapper.getToolBaseInfo(toolId);
		ToolBuyInfo toolBuyInfo = statisticalAnalysisMapper.getToolBuyInfo(toolId);
		if(!StringUtils.isBlank(toolBuyInfo.getManufactureDate())) {
			baseToolMainInfo.setManufactorDate(toolBuyInfo.getManufactureDate().substring(0, 10));
		}
		if(!StringUtils.isBlank(toolBuyInfo.getGetDate())) {
			baseToolMainInfo.setGetDate(toolBuyInfo.getGetDate().substring(0, 19));
		}
		if(!StringUtils.isBlank(baseToolMainInfo.getScrapDate())) {
			baseToolMainInfo.setScrapDate(baseToolMainInfo.getScrapDate().substring(0, 19));
		}
		baseToolMainInfo.setManufactorName(toolBuyInfo.getManufatorName());
		if(StringUtils.isEmpty(baseToolMainInfo.getModel())) {
			baseToolMainInfo.setTypeModel(baseToolMainInfo.getTypeName());
		}else {
			baseToolMainInfo.setTypeModel(baseToolMainInfo.getModel() + "-" + baseToolMainInfo.getTypeName());
		}
		Map map = new HashMap();
		map.put("baseToolMainInfo", baseToolMainInfo);
		return map;
	}

	@SuppressWarnings({ "unchecked", "rawtypes" })
	@Override
	public List<DeviceMainInfo> getDeviceInfoList() {
		List<DeviceMainInfo> orgDevicesByOrgId = statisticalAnalysisMapper.getOrgDevicesByOrgId();
		for (int i = 0; i < orgDevicesByOrgId.size(); i++) {
			//如果是方仓，需要判断三个仓的温湿度和门状态综合
			if(orgDevicesByOrgId.get(i).getDeviceType()==3) {
				Integer cangSynthesisDockStat = this.jdugeDockStat(
						orgDevicesByOrgId.get(i).getLeftDockState(), 
						orgDevicesByOrgId.get(i).getRightDockState(),
						Integer.parseInt(orgDevicesByOrgId.get(i).getDeviceState()));
				Integer cangSynthesisHumidityStat = 
						orgDevicesByOrgId.get(i).getLeftHumidityStat() &
						orgDevicesByOrgId.get(i).getRightHumidityStat() &
						Integer.parseInt(orgDevicesByOrgId.get(i).getHStat());
				Integer cangSynthesisTemperatureStat = 
						orgDevicesByOrgId.get(i).getLeftTemperatureStat() &
						orgDevicesByOrgId.get(i).getRightTemperatureStat() &
						Integer.parseInt(orgDevicesByOrgId.get(i).getTStat());
				orgDevicesByOrgId.get(i).setStateT(cangSynthesisDockStat);
				orgDevicesByOrgId.get(i).setCangSynthesisHumidityStat(cangSynthesisHumidityStat);
				orgDevicesByOrgId.get(i).setCangSynthesisTemperatureStat(cangSynthesisTemperatureStat);
			}
			List<Map> deviceToolsByDeviceId = statisticalAnalysisMapper.getDeviceToolsByDeviceId(orgDevicesByOrgId.get(i).getDeviceId());
			for (int j = 0; j < deviceToolsByDeviceId.size(); j++) {
				deviceToolsByDeviceId.get(j).put("imgPath", imgUtils.formatImgPath(FormatImgPre.PRE_TOOL.getValue() + deviceToolsByDeviceId.get(j).get("imgPath")));
			}
			orgDevicesByOrgId.get(i).setTools(deviceToolsByDeviceId);
		}
		return orgDevicesByOrgId;
	}
	
	private Integer jdugeDockStat(Integer leftDock, Integer rightDock, Integer downDock) {
		if(leftDock == -2 || rightDock == -2 || downDock == -2) {
			return -2;
		}
		
		if(leftDock == -1 || rightDock == -1 || downDock == -1) {
			return -1;
		}
		
		if(leftDock == 0 || rightDock == 0 || downDock == 0) {
			return 0;
		}
		
		return 1;
	}

	@Override
	public List<BaseTypeVO> selectImportantTool() {
		return statisticalAnalysisMapper.selectImportantTool();
	}

	@Override
	public Map<String,List<BaseTypeVO>> selectSummaryTool() {
		Map<String,List<BaseTypeVO>> result = new HashMap<String,List<BaseTypeVO>>();
		List<BaseTypeVO> datas = statisticalAnalysisMapper.selectSummaryTool();
		List<BaseTypeVO> total = datas.stream().filter(vo->vo.getType().equals(Integer.valueOf(1))).
				collect(Collectors.toList());
		result.put("total", total);
		datas.removeAll(total);
		result.put("detail", datas);
		return result;
	}

	@Override
	public List<BaseTypeVO> borrowSort() {
		return statisticalAnalysisMapper.borrowSort();
	}

	@Override
	public List<BaseTypeVO> manufatorSort() {
		return statisticalAnalysisMapper.manufatorSort();
	}

	@Override
	public Map<String,Object[]> statisPurchaseAndCrapt() {
		Map<String,Object[]> result = new HashMap<String,Object[]>();
		Integer[] years = DateUtils.produceContinueYearBy(4);
		result.put("axis_x", years);
		List<BaseTypeVO> mapper = statisticalAnalysisMapper.statisPurchaseAndCrapt();
		if(null != mapper && !mapper.isEmpty()) {
			Map<Integer,List<BaseTypeVO>> data = mapper.stream().collect(Collectors.groupingBy(BaseTypeVO::getType));
			Iterator<Entry<Integer,List<BaseTypeVO>>> entries = data.entrySet().iterator();
			while(entries.hasNext()) {
				Entry<Integer,List<BaseTypeVO>> inner = entries.next();
				Integer[] param = new Integer[4];
				for(int i=0;i<years.length;i++) {
					Boolean find = false;
					BaseTypeVO findParam = null;
					for(BaseTypeVO vo : inner.getValue()) {
						if(years[i].equals(Integer.parseInt(vo.getName()))) {
							find = true;
							findParam = vo;
							break;
						}
					}
					param[i]=0;
					if(find) {
						param[i] = Integer.parseInt(findParam.getValue().toString());
					}
				}
				result.put("value"+inner.getKey(), param);
			}
			return result;
		}
		return result;
	}

	@Override
	public Map<String,Object[]> statisBorrowAndReturn() {
		Map<String,Object[]> result = new HashMap<String,Object[]>();
		String[] months = DateUtils.produceContinueMonth(5);
		result.put("axis_x", months);
		List<BaseTypeVO> mapper = statisticalAnalysisMapper.statisBorrowAndReturn();
		if(null != mapper && !mapper.isEmpty()) {
			Map<Integer,List<BaseTypeVO>> data = mapper.stream().collect(Collectors.groupingBy(BaseTypeVO::getType));
			Iterator<Entry<Integer,List<BaseTypeVO>>> entries = data.entrySet().iterator();
			while(entries.hasNext()) {
				Entry<Integer,List<BaseTypeVO>> inner = entries.next();
				Integer[] param = new Integer[5];
				for(int i=0;i<months.length;i++) {
					Boolean find = false;
					BaseTypeVO findParam = null;
					for(BaseTypeVO vo : inner.getValue()) {
						if(months[i].equals(Integer.parseInt(vo.getName())+"月")) {
							find = true;
							findParam = vo;
							break;
						}
					}
					param[i]=0;
					if(find) {
						param[i] = Integer.parseInt(findParam.getValue().toString());
					}
				}
				result.put("value"+inner.getKey(), param);
			}
			return result;
		}
		return result;
	}

	@Override
	public Map<String,Object[]> statisInpsectAndExpired() {
		Map<String,Object[]> result = new HashMap<String,Object[]>();
		Integer[] years = DateUtils.produceContinueYearBy(4);
		result.put("axis_x", years);
		List<BaseTypeVO> mapper = statisticalAnalysisMapper.statisInpsectAndExpired();
		if(null != mapper && !mapper.isEmpty()) {
			Map<Integer,List<BaseTypeVO>> data = mapper.stream().collect(Collectors.groupingBy(BaseTypeVO::getType));
			Iterator<Entry<Integer,List<BaseTypeVO>>> entries = data.entrySet().iterator();
			while(entries.hasNext()) {
				Entry<Integer,List<BaseTypeVO>> inner = entries.next();
				Integer[] param = new Integer[4];
				for(int i=0;i<years.length;i++) {
					Boolean find = false;
					BaseTypeVO findParam = null;
					for(BaseTypeVO vo : inner.getValue()) {
						if(years[i].equals(Integer.parseInt(vo.getName()))) {
							find = true;
							findParam = vo;
							break;
						}
					}
					param[i]=0;
					if(find) {
						param[i] = Integer.parseInt(findParam.getValue().toString());
					}
				}
				result.put("value"+inner.getKey(), param);
			}
			return result;
		}
		return result;
	}

	@Override
	public Map<String,Object[]> statisToolTotalAndConfig() {
		Map<String,Object[]> result = new HashMap<String,Object[]>();
		Integer[] years = DateUtils.produceContinueYearBy(4);
		result.put("axis_x", years);
		List<BaseTypeVO> mapper = statisticalAnalysisMapper.statisToolTotalAndConfig();
		if(null != mapper && !mapper.isEmpty()) {
			Map<Integer,List<BaseTypeVO>> data = mapper.stream().collect(Collectors.groupingBy(BaseTypeVO::getType));
			Iterator<Entry<Integer,List<BaseTypeVO>>> entries = data.entrySet().iterator();
			while(entries.hasNext()) {
				Entry<Integer,List<BaseTypeVO>> inner = entries.next();
				Integer[] param = new Integer[4];
				for(int i=0;i<years.length;i++) {
					Boolean find = false;
					BaseTypeVO findParam = null;
					for(BaseTypeVO vo : inner.getValue()) {
						if(years[i].equals(Integer.parseInt(vo.getName()))) {
							find = true;
							findParam = vo;
							break;
						}
					}
					param[i]=0;
					if(find) {
						param[i] = Integer.parseInt(findParam.getValue().toString());
					}
				}
				result.put("value"+inner.getKey(), param);
			}
			return result;
		}
		return result;
	}

	@Override
	public int getNeedCheckToolNum() {
//		User user = WebUtils.user();
//		String orgId = String.valueOf(user.getOrgId());
		return statisticalAnalysisMapper.getNeedCheckToolNum();
	}

	@Override
	public int getExceptionNum() {
//		User user = WebUtils.user();
//		String orgId = String.valueOf(user.getOrgId());
		return statisticalAnalysisMapper.getExceptionNum();
	}
}
